<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="coinfaces">

        <title>什么推迟了bash的信号处理</title>

    <link rel="stylesheet" href="../../theme/css/style.css">
    <link rel="stylesheet" href="../../theme/css/pygments.css">



</head>

<body>
    <div class="content">
<h1>什么推迟了bash的信号处理</h1>    <p>
        under
            <a href="../../tags/bash/">bash</a>
            <a href="../../tags/signal/">signal</a>
    </p>
    <p>
        in <a href="../../categories/tech/">tech</a>
    </p>
    <p>Published: 2016-08-21</p>


    <p>在bash脚本里可以用trap设置信号处理命令，但不是所有情况下脚本收到信号都可以执行相应的命令，至少两种情况下信号处理会被推迟。</p>
<p>前台有外部命令运行时：</p>
<div class="highlight"><pre><span></span><span class="nb">trap</span> <span class="s1">&#39;echo Received SIGTERM&#39;</span> TERM
<span class="nb">echo</span> <span class="s2">&quot;Process </span><span class="nv">$$</span><span class="s2"> running&quot;</span>
cat
</pre></div>
<p>运行此脚本显示<tt class="docutils literal">Process 2390 running</tt>在另一个终端输入<tt class="docutils literal">kill 2390</tt>不会影响输出结果，输入<tt class="docutils literal"><span class="pre">Ctrl-D</span></tt>结束cat命令后才会显示<tt class="docutils literal">Received SIGTERM</tt>。</p>
<p>如果将最后的cat命令改为内置read命令，则不会推迟bash处理信号，但如果该命令在等待打开一个文件时便会，比如：</p>
<div class="highlight"><pre><span></span><span class="nb">trap</span> <span class="s1">&#39;echo Received SIGTERM&#39;</span> TERM
<span class="nb">echo</span> <span class="s2">&quot;Process </span><span class="nv">$$</span><span class="s2"> running&quot;</span>
rm -f fifo <span class="o">&amp;&amp;</span> mkfifo fifo
<span class="nb">read</span> &lt;fifo
</pre></div>
<p>在没有程序以写的方式打开命名管道文件fifo时，以读的方式打开命名管道便会引起阻塞，这时向进程发送的<tt class="docutils literal">SIGTERM</tt>信号，不会立即被处理，然后在另一终端运行<tt class="docutils literal">cat &gt;fifo</tt>后，fifo文件的读写端都被成功打开，这种情况下虽然前面输入的<tt class="docutils literal">SIGTERM</tt>信号还不会马上被处理，但如果再向进程发送<tt class="docutils literal">SIGTERM</tt>信号就会被立即处理。</p>
<p>如果将前面脚本的<tt class="docutils literal">read &lt;fifo</tt>改成<tt class="docutils literal">echo &gt;fifo</tt>，会在写入管道时打开文件阻塞，同样也会推迟bash信号处理。</p>
<p>编辑记录：</p>
<ul class="simple">
<li>2016-09-13，修改了一处笔误<tt class="docutils literal">cat fifo <span class="pre">-&gt;</span> cat &gt;fifo</tt></li>
</ul>
<p>（完）</p>

    </div>
<nav class="nav sidebar">
    <div class="siteinfo">
        <div class="sitename"><a href="../..">coinfaces</a></div>
        <div class="tagline">Another Side of Life</div>
    </div>

        <a href="../../categories/">categories</a>
        <a href="../..">&larr; Home</a>
</nav><footer class="footer">
    <span>
        &copy; jpli &middot;
        under <a rel="license" href="http://creativecommons.org/licenses/by-sa/4.0/">CC-BY-SA 4.0</a>
    </span>
    |
    <span>
        Powered by:
        <a href="http://blog.getpelican.com/">Pelican</a>
    </span>
</footer></body>
</html>